/**
 * 用户相关路由模块
 * @module userRoutes
 */
const express = require("express");
const router = express.Router();
const verifyToken = require("../utils/verifyToken");
const crypto = require("crypto");
const sqlconfig = require("../mysql/config");
const JWT = require("../utils/jwt");
const { createResponse } = require("../utils/responseHelper");
const { searchOne, insertOne } = require("../mysql/utils");
const {
  generateDeviceIdentifier,
  storeToken,
  deleteOldTokens,
  formatDateTime,
  cleanExpiredTokens,
  buildMenuTree
} = require("../utils/userUtils");

// 每小时运行一次清理任务
setInterval(cleanExpiredTokens, 3600000);
/**
 * POST /users/register
 * 用户注册
 */
router.post("/register", async function (req, res, next) {
  try {
    const sha256 = crypto.createHash("sha256");
    const { username, password } = req.body;

    // 检查用户名是否已存在
    const existingUser = await searchOne("users", "user_name", username);
    if (existingUser.length > 0) {
      return createResponse(res, "SERVER_ERROR", null, "用户名已存在");
    }

    // 加密密码
    const hashedPassword = sha256.update(password).digest("hex");

    // 设置用户角色、创建时间和登录系统权限
    const role = "USER";
    const timestamp = formatDateTime(new Date());
    const loginSystem = 2; // 默认只能登录C端前台

    // 插入新用户
    const sql = `
      INSERT INTO users (user_name, password, role, create_time, status, login_system)
      VALUES (?, ?, ?, ?, ?, ?)
    `;

    sqlconfig.query(sql, [username, hashedPassword, role, timestamp, 1, loginSystem], (error, results) => {
      if (error) {
        console.error("Error registering user:", error);
        return createResponse(res, "SERVER_ERROR", null, error.toString());
      }
      createResponse(res, "SUCCESS", null, "注册成功,请重新登录");
    });
  } catch (error) {
    createResponse(res, "SERVER_ERROR", null, error.toString());
  }
});

/**
 * POST /users/addUser
 * 添加用户（管理员功能）
 */
router.post("/addUser", async function (req, res, next) {
  try {
    const sha256 = crypto.createHash("sha256");
    const { username, password, role, loginSystem } = req.body;

    // 检查用户名是否已存在
    const existingUser = await searchOne("users", "user_name", username);
    if (existingUser.length > 0) {
      return createResponse(res, "SERVER_ERROR", null, "用户已存在");
    }

    const roleSign = role ? role : username === "admin" ? "ADMIN" : "USER";
    const hashedPassword = sha256.update(password).digest("hex");
    const timestamp = formatDateTime(new Date());

    const sql = `
      INSERT INTO users (user_name, password, role, create_time, status, login_system)
      VALUES (?, ?, ?, ?, ?, ?)
    `;

    sqlconfig.query(sql, [username, hashedPassword, roleSign, timestamp, 1, loginSystem], (error, results) => {
      if (error) {
        console.error("Error adding user:", error);
        return createResponse(res, "SERVER_ERROR", null, error.toString());
      }
      createResponse(res, "SUCCESS", null, "用户添加成功");
    });
  } catch (error) {
    createResponse(res, "SERVER_ERROR", null, error.toString());
  }
});

/**
 * POST /users/login
 * 用户登录
 */
router.post("/login", async function (req, res, next) {
  try {
    const crypto = require("crypto");
    const sha256 = crypto.createHash("sha256");
    const { username, password, loginSystem } = req.body; // loginSystem: 1 表示 CMS，2 表示 C 端

    // 验证必要的输入
    if (!username || !password || !loginSystem) {
      return createResponse(res, "SERVER_ERROR", null, "用户名、密码或系统类型不能为空");
    }

    // 创建登录用户对象，包含加密后的密码
    const loginUser = {
      username,
      password: sha256.update(password).digest("hex")
    };

    // 获取用户的IP地址
    const lastloginIp = req.ip.split(":")[req.ip.split(":").length - 1];

    // 查询用户信息
    const sql = `SELECT * FROM users WHERE user_name=? AND password=?`;
    sqlconfig.query(sql, [loginUser.username, loginUser.password], async (err, result) => {
      if (err) {
        console.error("Database query error:", err);
        return createResponse(res, "SERVER_ERROR", null, "数据库查询错误，请稍后重试");
      }

      if (result.length === 0) {
        return createResponse(res, "SERVER_ERROR", null, "用户名或密码错误");
      } else if (result[0].status == 0) {
        return createResponse(
          res,
          "SERVER_ERROR",
          null,
          `您的账户被停用，原因是：${result[0].disable_reason}`
        );
      } else {
        const data = result[0];
        
        // 检查登录系统权限
        if ((loginSystem == 1 && data.login_system == 2) || (loginSystem == 2 && data.login_system == 1)) {
          return createResponse(res, "SERVER_ERROR", null, "您没有权限登录此系统");
        }

        // 更新用户最后登录时间和IP
        const timestamp = formatDateTime(new Date());
        const updateSql = `UPDATE users SET last_login_time=?, last_login_ip=? WHERE user_id=?`;
        
        sqlconfig.query(updateSql, [timestamp, lastloginIp, data.user_id], async (updateErr, updateResult) => {
          if (updateErr) {
            console.error("Error updating user login info:", updateErr);
            return createResponse(res, "SERVER_ERROR", null, "更新用户登录信息失败");
          }

          const deviceIdentifier = generateDeviceIdentifier(req);
          const ip = req.ip || req.connection.remoteAddress;
          const userAgent = req.headers["user-agent"] || "";

          try {
            // 删除同一系统的旧 token
            await deleteOldTokens(data.user_id.toString(), loginSystem);
          
            // 创建新token并存储
            const token = JWT.createToken(data.user_id, deviceIdentifier);
            await storeToken(data.user_id.toString(), token, ip, userAgent, loginSystem);
          
            createResponse(res, "SUCCESS", null, "登录成功", token);
          } catch (error) {
            console.error("Error during login process:", error);
            let errorMessage = "登录过程中出现错误，请稍后重试";
            if (error.code === 'ER_NO_SUCH_TABLE') {
              errorMessage = "数据库表不存在，请联系管理员";
            } else if (error.code === 'ER_ACCESS_DENIED_ERROR') {
              errorMessage = "数据库访问被拒绝，请检查数据库配置";
            }
            // 移除了 ER_DUP_ENTRY 的处理，因为它不应该再出现
            createResponse(res, "SERVER_ERROR", null, errorMessage);
          }
        });
      }
    });
  } catch (error) {
    console.error("Unexpected error during login:", error);
    createResponse(res, "SERVER_ERROR", null, "登录过程中发生意外错误，请稍后重试");
  }
});

/**
 * POST /users/logout
 * 用户退出登录
 */
router.post("/logout", verifyToken, (req, res) => {
  // 从验证中间件获取用户ID
  const userId = req.user.userId.toString();
  // 从请求体获取登录系统类型
  const loginSystem = req.body.loginSystem; // 1 表示 CMS，2 表示 C 端

  // 验证 loginSystem 参数
  if (!loginSystem) {
    return createResponse(res, "SERVER_ERROR", null, "系统类型不能为空");
  }

  // 从数据库中删除该用户特定系统的token
  const sql = "DELETE FROM tokens WHERE user_id = ? AND login_system = ?";
  sqlconfig.query(sql, [userId, loginSystem], (err, result) => {
    if (err) {
      console.error("Error deleting tokens:", err);
      return createResponse(res, "SERVER_ERROR", null, "退出登录失败");
    }

    // 检查是否有token被删除
    if (result.affectedRows === 0) {
      return createResponse(res, "SUCCESS", null, "没有找到需要删除的登录信息");
    }

    createResponse(res, "SUCCESS", null, "退出登录成功");
  });
});
/**
 * GET /users/getUserInfo
 * 获取用户信息和菜单
 */
router.get("/getUserInfo", verifyToken, (req, res, next) => {
  try {
    const userId = req.user.userId;
    const system = req.query.system
    const userSql = `
      SELECT 
        user_id,
        user_name AS userName, 
        role, 
        create_time AS createTime, 
        last_login_time AS lastLoginTime 
      FROM users 
      WHERE user_id=?
    `;

    sqlconfig.query(userSql, [userId], (err, userResult) => {
      if (err) {
        return createResponse(res, "SERVER_ERROR", null, err.toString());
      }

      if (userResult.length === 0) {
        return createResponse(res, "SERVER_ERROR", null, "未找到用户信息");
      }

      const userInfo = userResult[0];
      // 格式化时间
      userInfo.createTime = formatDateTime(userInfo.createTime);
      userInfo.lastLoginTime = formatDateTime(userInfo.lastLoginTime);
      userInfo.userId=userInfo.user_id
      let menuSql;

      if (userInfo.role === "ADMIN") {
        menuSql = `
          SELECT id, parent_id AS parentId, menu_type AS menuType, menu_name AS menuName, path, component, icon, sort_order AS sortOrder, is_route AS isRoute, is_hidden AS isHidden, is_cached AS isCached
          FROM menus
          ORDER BY sort_order ASC
        `;
      } else {
        menuSql = `
          SELECT id, parent_id AS parentId, menu_type AS menuType, menu_name AS menuName, path, component, icon, sort_order AS sortOrder, is_route AS isRoute, is_hidden AS isHidden, is_cached AS isCached
          FROM menus
          WHERE FIND_IN_SET('USER', permissions) > 0
          ORDER BY sort_order ASC
        `;
      }

      sqlconfig.query(menuSql, (err, menuResult) => {
        if (err) {
          return createResponse(res, "SERVER_ERROR", null, err.toString());
        }

        const menuTree = buildMenuTree(menuResult);
        const responseData = {
          ...userInfo,
        };
        // c端社区不返回menus字段
        if (!system || system == 1) {
          responseData.menus = menuTree
        }
        createResponse(
          res,
          "SUCCESS",
          responseData,
          "获取用户信息和菜单成功"
        );
      });
    });
  } catch (error) {
    createResponse(res, "SERVER_ERROR", null, error.toString());
  }
});

/**
 * GET /users/getUserList
 * 获取用户列表
 */
router.get("/getUserList", verifyToken, async (req, res) => {
  try {
    const { username, role, loginSystem } = req.query;

    let sql = `
      SELECT 
        user_id AS userId, 
        user_name AS username, 
        role, 
        create_time AS createTime, 
        last_login_time AS lastLoginTime, 
        last_login_ip AS lastLoginIp, 
        status,
        disable_reason AS disableReason,
        login_system AS loginSystem
      FROM users
      WHERE 1=1
    `;

    const params = [];

    if (username) {
      sql += ` AND user_name LIKE ?`;
      params.push(`%${username}%`);
    }

    if (role) {
      sql += ` AND role = ?`;
      params.push(role);
    }

    if (loginSystem) {
      sql += ` AND login_system = ?`;
      params.push(loginSystem);
    }

    sqlconfig.query(sql, params, (err, result) => {
      if (err) {
        return createResponse(res, "SERVER_ERROR", null, err.toString());
      }
      // 格式化时间
      result.forEach(user => {
        user.createTime = user.createTime ? formatDateTime(user.createTime) : null;
        user.lastLoginTime = user.lastLoginTime ? formatDateTime(user.lastLoginTime) : null;
      });
      createResponse(res, "SUCCESS", result, "获取用户列表成功");
    });
  } catch (error) {
    createResponse(res, "SERVER_ERROR", null, error.toString());
  }
});
/**
 * DELETE /users/deleteUser/:userId
 * 删除用户
 */
router.delete("/deleteUser/:userId", verifyToken, async (req, res) => {
  try {
    const {
      userId
    } = req.params;
    const sql = "DELETE FROM users WHERE user_id = ?";
    sqlconfig.query(sql, [userId], (err, result) => {
      if (err) {
        return createResponse(res, "SERVER_ERROR", null, err.toString());
      }
      if (result.affectedRows === 0) {
        return createResponse(res, "SERVER_ERROR", null, "用户不存在");
      }
      createResponse(res, "SUCCESS", null, "删除用户成功");
    });
  } catch (error) {
    createResponse(res, "SERVER_ERROR", null, error.toString());
  }
});

/**
 * PUT /users/updateUserStatus/:userId
 * 更新用户状态
 */
router.put("/updateUserStatus/:userId", verifyToken, async (req, res) => {
  try {
    const {
      userId
    } = req.params;
    const {
      status,
      disableReason
    } = req.body;
    console.log(status, disableReason);
    if (status == 0 && !disableReason) {
      return createResponse(res, "SERVER_ERROR", null, "停用原因不能为空");
    }
    const sql = "UPDATE users SET status = ?, disable_reason = ? WHERE user_id = ?";
    sqlconfig.query(sql, [status, disableReason, userId], (err, result) => {
      if (err) {
        return createResponse(res, "SERVER_ERROR", null, err.toString());
      }
      if (result.affectedRows === 0) {
        return createResponse(res, "SERVER_ERROR", null, "用户不存在");
      }
      createResponse(res, "SUCCESS", null, "更新用户状态成功");
    });
  } catch (error) {
    createResponse(res, "SERVER_ERROR", null, error.toString());
  }
});



module.exports = router;